# coding: utf-8

import os
import tensorflow as tf
import tensorflow.contrib.keras as kr


# from project.myApp.forecast.cnn_rnn import rnn_model
# from project.myApp.forecast.cnn_rnn import cnn_model

# from .cnn_rnn import rnn_model,cnn_model
# import os
# print(os.get_exec_path()[0])
save_path = './myApp/forecast/checkpoints/textrnn/best_validation'
save_path1 = './myApp/forecast/checkpoints/textcnn/best_validation'
# coding: utf-8

# import tensorflow as tf


class TCNNConfig(object):
    """CNN配置参数"""

    embedding_dim = 64  # 词向量维度
    seq_length = 600  # 序列长度
    num_classes = 7  # 类别数
    # num_classes = 10  # 类别数
    num_filters = 256  # 卷积核数目
    kernel_size = 5  # 卷积核尺寸
    vocab_size = 5000  # 词汇表达小

    hidden_dim = 128  # 全连接层神经元

    dropout_keep_prob = 0.5  # dropout保留比例
    learning_rate = 1e-3  # 学习率

    batch_size = 64  # 每批训练大小
    # batch_size = 128  # 每批训练大小
    num_epochs = 100  # 总迭代轮次

    print_per_batch = 2  # 每多少轮输出一次结果
    save_per_batch = 10  # 每多少轮存入tensorboard
#!/usr/bin/python
# -*- coding: utf-8 -*-

import tensorflow as tf

class TRNNConfig(object):
    """RNN配置参数"""

    # 模型参数
    embedding_dim = 64      # 词向量维度
    seq_length = 600        # 序列长度
    # seq_length = 7        # 序列长度
    # num_classes = 10        # 类别数

    num_classes = 7        # 类别数
    vocab_size = 5000       # 词汇表达小

    num_layers= 2           # 隐藏层层数
    hidden_dim = 128        # 隐藏层神经元
    rnn = 'gru'             # lstm 或 gru

    dropout_keep_prob = 0.8 # dropout保留比例
    learning_rate = 1e-3    # 学习率

    batch_size = 64         # 每批训练大小
    num_epochs = 150          # 总迭代轮次
    # num_epochs = 1          # 总迭代轮次

    print_per_batch = 2    # 每多少轮输出一次结果
    save_per_batch = 10      # 每多少轮存入tensorboard


class TextRNN(object):
    """文本分类，RNN模型"""
    def __init__(self, config):
        self.config = config
        tf.reset_default_graph()
        # 三个待输入的数据
        self.input_x = tf.placeholder(tf.int32, [None, self.config.seq_length], name='input_x')
        self.input_y = tf.placeholder(tf.float32, [None, self.config.num_classes], name='input_y')
        self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')

        self.rnn()

    def rnn(self):
        """rnn模型"""

        def lstm_cell():   # lstm核
            return tf.contrib.rnn.BasicLSTMCell(self.config.hidden_dim, state_is_tuple=True)

        def gru_cell():  # gru核
            return tf.contrib.rnn.GRUCell(self.config.hidden_dim)

        def dropout(): # 为每一个rnn核后面加一个dropout层
            if (self.config.rnn == 'lstm'):
                cell = lstm_cell()
            else:
                cell = gru_cell()
            return tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.keep_prob)

        # 词向量映射
        with tf.device('/cpu:0'):
            embedding = tf.get_variable('embedding', [6000, self.config.embedding_dim])
            embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)

        with tf.name_scope("rnn"):
            # 多层rnn网络
            cells = [dropout() for _ in range(self.config.num_layers)]
            rnn_cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)

            _outputs, _ = tf.nn.dynamic_rnn(cell=rnn_cell, inputs=embedding_inputs, dtype=tf.float32)
            last = _outputs[:, -1, :]  # 取最后一个时序输出作为结果

        with tf.name_scope("score"):
            # 全连接层，后面接dropout以及relu激活
            fc = tf.layers.dense(last, self.config.hidden_dim, name='fc1')
            fc = tf.contrib.layers.dropout(fc, self.keep_prob)
            fc = tf.nn.relu(fc)

            # 分类器
            self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2')
            self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1)  # 预测类别

        with tf.name_scope("optimize"):
            # 损失函数，交叉熵
            cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)
            self.loss = tf.reduce_mean(cross_entropy)
            # 优化器
            self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)

        with tf.name_scope("accuracy"):
            # 准确率
            correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls)
            self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))


class TextCNN(object):
    """文本分类，CNN模型"""

    def __init__(self, config):
        self.config = config
        tf.reset_default_graph()
        # 三个待输入的数据
        self.input_x = tf.placeholder(tf.int32, [None, self.config.seq_length], name='input_x')
        self.input_y = tf.placeholder(tf.float32, [None, self.config.num_classes], name='input_y')
        self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')

        self.cnn()

    def cnn(self):
        """CNN模型"""
        # 词向量映射
        # tf.reset_default_graph()
        with tf.device('/cpu:0'):
            embedding = tf.get_variable('embedding', [6000, self.config.embedding_dim])
            embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)

        with tf.name_scope("cnn"):
            # CNN layer
            conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv')
            # global max pooling layer
            gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp')

        with tf.name_scope("score"):
            # 全连接层，后面接dropout以及relu激活
            fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1')
            fc = tf.contrib.layers.dropout(fc, self.keep_prob)
            fc = tf.nn.relu(fc)

            # 分类器
            self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2')
            self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1)  # 预测类别

        with tf.name_scope("optimize"):
            # 损失函数，交叉熵
            cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)
            self.loss = tf.reduce_mean(cross_entropy)
            # 优化器
            self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)

        with tf.name_scope("accuracy"):
            # 准确率
            correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls)
            self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))



class RnnModel:
    def __init__(self):
        self.config = TRNNConfig()
        self.config.vocab_size = 6000
        self.model = TextRNN(self.config)

        self.session = tf.Session()
        self.session.run(tf.compat.v1.global_variables_initializer())
        saver = tf.compat.v1.train.Saver()
        saver.restore(sess=self.session, save_path=save_path)  # 读取保存的模型

    def predict(self, message):
        feed_dict = {
            self.model.input_x: kr.preprocessing.sequence.pad_sequences([message], self.config.seq_length),
            self.model.keep_prob: 1.0
        }
        y_pred_cls = self.session.run(self.model.y_pred_cls, feed_dict=feed_dict)
        if y_pred_cls[0]==0:
            return 'A'
        if y_pred_cls[0]==1:
            return 'B'
        if y_pred_cls[0]==2:
            return 'C'
        if y_pred_cls[0]==3:
            return 'D'
        if y_pred_cls[0]==4:
            return 'E'
        # return y_pred_cls[0]

class CnnModel:
    def __init__(self):
        self.config = TCNNConfig()
        self.config.vocab_size = 6000
        self.model = TextCNN(self.config)

        self.session = tf.Session()
        self.session.run(tf.compat.v1.global_variables_initializer())
        saver = tf.compat.v1.train.Saver()
        saver.restore(sess=self.session, save_path=save_path1)  # 读取保存的模型

    def predict(self, message):
        feed_dict = {
            self.model.input_x: kr.preprocessing.sequence.pad_sequences([message], self.config.seq_length),
            self.model.keep_prob: 1.0
        }
        y_pred_cls = self.session.run(self.model.y_pred_cls, feed_dict=feed_dict)
        # 0-20 A 0
        # 20-30 B 1
        # 30-40 C 2
        # 40-50 D 3
        # >=50 E 4
        if y_pred_cls[0]==0:
            return 'A'
        if y_pred_cls[0]==1:
            return 'B'
        if y_pred_cls[0]==2:
            return 'C'
        if y_pred_cls[0]==3:
            return 'D'
        if y_pred_cls[0]==4:
            return 'E'



def get_rnndata(data):
    # data[4] = int(data[4])
    rnn_model = RnnModel()
    re = rnn_model.predict(data)
    print(re)
    return re

def get_cnndata(data):
    # data[4] = int(data[4])
    cnn_model = CnnModel()
    re = cnn_model.predict(data)
    print(re)
    return re

# if __name__ == '__main__':

# get_cnndata([99,74,124,20,1.5,73,59])


# if __name__ == '__main__':
#     rnn_model = RnnModel()
#     # test_demo = ['三星ST550以全新的拍摄方式超越了以往任何一款数码相机',
#     # '热火vs骑士前瞻：皇帝回乡二番战 东部次席唾手可得新浪体育讯北京时间3月30日7:00']
#     # for i in test_demo:
#     #     print(cnn_model.predict(i))
#     # test_demo = '三星ST550以全新的拍摄方式超越了以往任何一款数码相机'
#     # test_demo = [97, 72, 123, 15, 1, 38, 101]
#     # test_demo = [50,33,51,20,0.9,33,63]#21
#     test_demo = [99,74,124,20,1.5,73,59]
#
#     print(rnn_model.predict(test_demo))
